using Microsoft.AspNetCore.SignalR;
using Microsoft.AspNetCore.Authorization;
using CollabApp.Application.Interfaces;
using CollabApp.Application.DTOs.Game;
using CollabApp.Domain.ValueObjects;
using System.Security.Claims;
using Microsoft.Extensions.Logging;
using System.Collections.Concurrent;

namespace CollabApp.API.Hubs
{
    /// <summary>
    /// 画线圈地游戏专用Hub
    /// 处理画线、移动、圈地、道具等实时游戏逻辑
    /// 注意: 游戏创建由 RoomController 处理，此Hub专注于游戏内交互
    /// </summary>
    [Authorize]
    public class LineDrawingGameHub : Hub
    {
        private readonly ILineDrawingGameService _gameService;
        private readonly ILogger<LineDrawingGameHub> _logger;
        
        // 静态字典追踪每个游戏的连接玩家 <gameId, <userId, connectionId>>
        private static readonly ConcurrentDictionary<string, ConcurrentDictionary<string, string>> _gameConnections = new();

        public LineDrawingGameHub(
            ILineDrawingGameService gameService,
            ILogger<LineDrawingGameHub> logger)
        {
            _gameService = gameService;
            _logger = logger;
        }

        /// <summary>
        /// 玩家加入游戏房间（仅用于游戏内交互，游戏创建由RoomController处理）
        /// </summary>
        /// <param name="gameId">游戏ID</param>
        public async Task JoinGame(string gameId)
        {
            try
            {
                var userId = GetCurrentUserId();
                var userName = GetCurrentUserName();
                _logger.LogInformation("=== 玩家加入游戏 === UserId: {UserId}, UserName: {UserName}, GameId: {GameId}, ConnectionId: {ConnectionId}", 
                    userId, userName, gameId, Context.ConnectionId);
                    
                await Groups.AddToGroupAsync(Context.ConnectionId, $"Game_{gameId}");
                _logger.LogInformation("玩家已加入SignalR组: Game_{GameId}", gameId);
                
                // 记录玩家连接
                var gameConnections = _gameConnections.GetOrAdd(gameId, _ => new ConcurrentDictionary<string, string>());
                gameConnections.AddOrUpdate(userId.ToString(), Context.ConnectionId, (key, oldValue) => Context.ConnectionId);
                _logger.LogInformation("玩家连接已记录，当前游戏连接数: {ConnectionCount}", gameConnections.Count);
                
                // 获取当前游戏状态并发送给客户端
                if (Guid.TryParse(gameId, out var parsedGameId))
                {
                    _logger.LogInformation("获取游戏状态: {ParsedGameId}", parsedGameId);
                    var gameState = await _gameService.GetGameStateAsync(parsedGameId);
                    if (gameState != null)
                    {
                        _logger.LogInformation("获取到游戏状态 - Status: {Status}, PlayerCount: {PlayerCount}", 
                            gameState.Status, gameState.Players?.Count ?? 0);
                            
                        if (gameState.Players?.Any() == true)
                        {
                            foreach (var player in gameState.Players)
                            {
                                _logger.LogInformation("发送前玩家状态 - PlayerId: {PlayerId}, Username: {Username}, IsAlive: {IsAlive}", 
                                    player.PlayerId, player.Username, player.IsAlive);
                            }
                        }
                        
                        _logger.LogInformation("发送GameStateUpdate到客户端...");
                        await Clients.Caller.SendAsync("GameStateUpdate", gameState);
                        _logger.LogInformation("GameStateUpdate发送完成");
                        
                        // 发送排行榜给新加入的玩家
                        _logger.LogInformation("🎯 为新加入玩家获取排行榜 - GameId: {GameId}, PlayerId: {PlayerId}", gameId, userId);
                        var rankings = await _gameService.GetRealTimeRankingAsync(parsedGameId);
                        
                        _logger.LogInformation("🎯 新加入玩家排行榜条目数: {Count}", rankings?.Count ?? 0);
                        if (rankings?.Any() == true)
                        {
                            foreach (var ranking in rankings)
                            {
                                _logger.LogInformation("🎯 新加入玩家排行榜条目 - Rank: {Rank}, PlayerId: {PlayerId}, Username: {Username}, TerritoryArea: {TerritoryArea}",
                                    ranking.Rank, ranking.PlayerId, ranking.Username, ranking.TerritoryArea);
                            }
                        }
                        
                        await Clients.Caller.SendAsync("RankingUpdate", new
                        {
                            rankings = rankings,
                            timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                        });
                        _logger.LogInformation("🎯 新加入玩家排行榜发送完成");
                        
                        // 通知游戏内所有玩家有新玩家连接
                        await Clients.Group($"Game_{gameId}").SendAsync("PlayerConnectionUpdate", new
                        {
                            PlayerId = userId.ToString(),
                            Username = userName,
                            IsConnected = true,
                            ConnectedCount = gameConnections.Count,
                            TotalPlayers = gameState.Players?.Count ?? 0
                        });
                    }
                }
                
                _logger.LogInformation("玩家加入游戏: UserId={UserId}, GameId={GameId}", userId, gameId);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "玩家加入游戏失败: GameId={GameId}", gameId);
                await Clients.Caller.SendAsync("Error", "加入游戏失败");
            }
        }

        /// <summary>
        /// 玩家离开游戏房间
        /// </summary>
        /// <param name="gameId">游戏ID</param>
        public async Task LeaveGame(string gameId)
        {
            try
            {
                var userId = GetCurrentUserId();
                var userName = GetCurrentUserName();
                await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"Game_{gameId}");
                
                // 移除玩家连接记录
                if (_gameConnections.TryGetValue(gameId, out var gameConnections))
                {
                    gameConnections.TryRemove(userId.ToString(), out _);
                    
                    // 通知其他玩家有玩家断开连接
                    await Clients.Group($"Game_{gameId}").SendAsync("PlayerConnectionUpdate", new
                    {
                        PlayerId = userId.ToString(),
                        Username = userName,
                        IsConnected = false,
                        ConnectedCount = gameConnections.Count
                    });
                    
                    // 如果游戏没有玩家了，清理游戏连接记录
                    if (gameConnections.IsEmpty)
                    {
                        _gameConnections.TryRemove(gameId, out _);
                    }
                }
                
                _logger.LogInformation("玩家离开游戏: UserId={UserId}, GameId={GameId}", userId, gameId);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "玩家离开游戏失败: GameId={GameId}", gameId);
            }
        }

        /// <summary>
        /// 玩家移动
        /// </summary>
        /// <param name="gameId">游戏ID</param>
        /// <param name="x">X坐标</param>
        /// <param name="y">Y坐标</param>
        /// <param name="timestamp">时间戳</param>
        public async Task PlayerMove(string gameId, float x, float y, long timestamp)
        {
            try
            {
                if (!Guid.TryParse(gameId, out var parsedGameId))
                {
                    await Clients.Caller.SendAsync("Error", "无效的游戏ID");
                    return;
                }

                var userId = GetCurrentUserId();
                var position = new Position(x, y);
                
                var result = await _gameService.ProcessPlayerMoveAsync(parsedGameId, userId, position, timestamp);
                
                if (result.Success)
                {
                    // 广播移动成功给所有玩家
                    await Clients.Group($"Game_{gameId}").SendAsync("PlayerMoved", new
                    {
                        PlayerId = userId,
                        Position = new { X = x, Y = y },
                        MovementSpeed = result.MovementSpeed,
                        IsInEnemyTerritory = result.IsInEnemyTerritory,
                        CanStartDrawing = result.CanStartDrawing,
                        Timestamp = timestamp
                    });
                    
                    // 🔥 关键修复：广播完整游戏状态以更新所有玩家位置
                    var gameState = await _gameService.GetGameStateAsync(parsedGameId);
                    if (gameState != null)
                    {
                        // 添加调试信息：显示当前玩家的轨迹状态
                        var currentPlayer = gameState.Players?.FirstOrDefault(p => p.PlayerId == userId);
                        if (currentPlayer != null)
                        {
                            _logger.LogInformation("移动后游戏状态 - PlayerId: {PlayerId}, IsDrawing: {IsDrawing}, PathCount: {PathCount}", 
                                userId, currentPlayer.IsDrawing, currentPlayer.CurrentPath?.Count ?? 0);
                        }
                        
                        await Clients.Group($"Game_{gameId}").SendAsync("GameStateUpdate", gameState);
                        _logger.LogInformation("移动后广播游戏状态完成 - PlayerId: {PlayerId}, X: {X}, Y: {Y}", userId, x, y);
                    }
                }
                else
                {
                    await Clients.Caller.SendAsync("MoveRejected", new
                    {
                        Errors = result.Errors,
                        Timestamp = timestamp
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "处理玩家移动失败: GameId={GameId}, X={X}, Y={Y}", gameId, x, y);
                await Clients.Caller.SendAsync("Error", "移动失败");
            }
        }

        /// <summary>
        /// 开始画线
        /// </summary>
        /// <param name="gameId">游戏ID</param>
        /// <param name="x">起始X坐标</param>
        /// <param name="y">起始Y坐标</param>
        /// <param name="timestamp">时间戳</param>
        public async Task StartDrawing(string gameId, float x, float y, long timestamp)
        {
            try
            {
                if (!Guid.TryParse(gameId, out var parsedGameId))
                {
                    await Clients.Caller.SendAsync("Error", "无效的游戏ID");
                    return;
                }

                var userId = GetCurrentUserId();
                var position = new Position(x, y);
                
                var result = await _gameService.StartDrawingAsync(parsedGameId, userId, position, timestamp);
                
                if (result.Success)
                {
                    // 广播开始画线
                    await Clients.Group($"Game_{gameId}").SendAsync("DrawingStarted", new
                    {
                        PlayerId = userId,
                        StartPosition = new { X = x, Y = y },
                        Timestamp = timestamp
                    });
                }
                else
                {
                    await Clients.Caller.SendAsync("DrawingRejected", new
                    {
                        Errors = result.Errors,
                        Timestamp = timestamp
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "开始画线失败: GameId={GameId}, X={X}, Y={Y}", gameId, x, y);
                await Clients.Caller.SendAsync("Error", "开始画线失败");
            }
        }

        /// <summary>
        /// 添加画线路径点
        /// </summary>
        /// <param name="gameId">游戏ID</param>
        /// <param name="x">X坐标</param>
        /// <param name="y">Y坐标</param>
        /// <param name="timestamp">时间戳</param>
        public async Task AddPathPoint(string gameId, float x, float y, long timestamp)
        {
            try
            {
                if (!Guid.TryParse(gameId, out var parsedGameId))
                {
                    await Clients.Caller.SendAsync("Error", "无效的游戏ID");
                    return;
                }

                var userId = GetCurrentUserId();
                var position = new Position(x, y);
                
                var result = await _gameService.AddPathPointAsync(parsedGameId, userId, position, timestamp);
                
                if (result.Success)
                {
                    // 广播路径点
                    await Clients.Group($"Game_{gameId}").SendAsync("PathPointAdded", new
                    {
                        PlayerId = userId,
                        Point = new { X = x, Y = y },
                        PathLength = result.PathLength,
                        Timestamp = timestamp
                    });
                }
                else
                {
                    await Clients.Caller.SendAsync("PathPointRejected", new
                    {
                        Errors = result.Errors,
                        CollisionDetected = result.CollisionDetected,
                        CollidedWithPlayerId = result.CollidedWithPlayerId,
                        Timestamp = timestamp
                    });

                    // 如果检测到碰撞导致死亡，广播死亡事件
                    if (result.CollisionDetected)
                    {
                        await Clients.Group($"Game_{gameId}").SendAsync("PlayerDied", new
                        {
                            PlayerId = userId,
                            DeathReason = "碰撞",
                            KillerPlayerId = result.CollidedWithPlayerId,
                            Position = new { X = x, Y = y },
                            Timestamp = timestamp
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加路径点失败: GameId={GameId}, X={X}, Y={Y}", gameId, x, y);
                await Clients.Caller.SendAsync("Error", "画线失败");
            }
        }

        /// <summary>
        /// 完成圈地
        /// </summary>
        /// <param name="gameId">游戏ID</param>
        /// <param name="x">结束X坐标</param>
        /// <param name="y">结束Y坐标</param>
        /// <param name="timestamp">时间戳</param>
        public async Task CompleteDrawing(string gameId, float x, float y, long timestamp)
        {
            try
            {
                if (!Guid.TryParse(gameId, out var parsedGameId))
                {
                    await Clients.Caller.SendAsync("Error", "无效的游戏ID");
                    return;
                }

                var userId = GetCurrentUserId();
                var position = new Position(x, y);
                
                var result = await _gameService.CompleteDrawingAsync(parsedGameId, userId, position, timestamp);
                
                if (result.Success)
                {
                    // 广播圈地成功
                    await Clients.Group($"Game_{gameId}").SendAsync("TerritoryCompleted", new
                    {
                        PlayerId = userId,
                        EndPosition = new { X = x, Y = y },
                        NewTerritoryArea = result.NewTerritoryArea,
                        TotalTerritoryArea = result.TotalTerritoryArea,
                        EngulfedArea = result.EngulfedArea,
                        NewRank = result.NewRank,
                        Timestamp = timestamp
                    });

                    // 如果有领地被吞噬，广播相关信息
                    if (result.EngulfedArea > 0)
                    {
                        await Clients.Group($"Game_{gameId}").SendAsync("TerritoriesEngulfed", new
                        {
                            EngulferId = userId,
                            EngulfedTerritories = result.EngulfedTerritories.Select(t => new
                            {
                                Area = t.Area,
                                // 可以添加更多领地信息
                            }),
                            Timestamp = timestamp
                        });
                    }

                    // 广播实时排名更新
                    _logger.LogInformation("🎯 获取并广播排行榜 - GameId: {GameId}", gameId);
                    var rankings = await _gameService.GetRealTimeRankingAsync(parsedGameId);
                    
                    _logger.LogInformation("🎯 获取到排行榜条目数: {Count}", rankings?.Count ?? 0);
                    if (rankings?.Any() == true)
                    {
                        foreach (var ranking in rankings)
                        {
                            _logger.LogInformation("🎯 排行榜条目广播前 - Rank: {Rank}, PlayerId: {PlayerId}, Username: {Username}, TerritoryArea: {TerritoryArea}",
                                ranking.Rank, ranking.PlayerId, ranking.Username, ranking.TerritoryArea);
                        }
                    }
                    
                    await Clients.Group($"Game_{gameId}").SendAsync("RankingUpdate", new
                    {
                        rankings = rankings,
                        timestamp = timestamp
                    });
                    
                    _logger.LogInformation("🎯 排行榜广播完成 - GameId: {GameId}, Group: Game_{GameId}", gameId, gameId);
                }
                else
                {
                    await Clients.Caller.SendAsync("TerritoryRejected", new
                    {
                        Errors = result.Errors,
                        Timestamp = timestamp
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "完成圈地失败: GameId={GameId}, X={X}, Y={Y}", gameId, x, y);
                await Clients.Caller.SendAsync("Error", "圈地失败");
            }
        }

        /// <summary>
        /// 使用道具
        /// </summary>
        /// <param name="gameId">游戏ID</param>
        /// <param name="powerUpType">道具类型</param>
        /// <param name="timestamp">时间戳</param>
        public async Task UsePowerUp(string gameId, int powerUpType, long timestamp)
        {
            try
            {
                if (!Guid.TryParse(gameId, out var parsedGameId))
                {
                    await Clients.Caller.SendAsync("Error", "无效的游戏ID");
                    return;
                }

                var userId = GetCurrentUserId();
                var powerUp = (PowerUpType)powerUpType;
                
                var result = await _gameService.UsePowerUpAsync(parsedGameId, userId, powerUp, timestamp);
                
                if (result.Success)
                {
                    // 广播道具使用
                    await Clients.Group($"Game_{gameId}").SendAsync("PowerUpUsed", new
                    {
                        PlayerId = userId,
                        PowerUpType = powerUpType,
                        Effect = result.Effect,
                        DurationMs = result.DurationMs,
                        EffectParameters = result.EffectParameters,
                        Timestamp = timestamp
                    });
                }
                else
                {
                    await Clients.Caller.SendAsync("PowerUpRejected", new
                    {
                        Errors = result.Errors,
                        Timestamp = timestamp
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "使用道具失败: GameId={GameId}, PowerUpType={PowerUpType}", gameId, powerUpType);
                await Clients.Caller.SendAsync("Error", "使用道具失败");
            }
        }

        /// <summary>
        /// 请求游戏状态同步
        /// </summary>
        /// <param name="gameId">游戏ID</param>
        public async Task RequestGameState(string gameId)
        {
            try
            {
                if (!Guid.TryParse(gameId, out var parsedGameId))
                {
                    await Clients.Caller.SendAsync("Error", "无效的游戏ID");
                    return;
                }

                var gameState = await _gameService.GetGameStateAsync(parsedGameId);
                if (gameState != null)
                {
                    await Clients.Caller.SendAsync("GameStateUpdate", gameState);
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "请求游戏状态失败: GameId={GameId}", gameId);
                await Clients.Caller.SendAsync("Error", "获取游戏状态失败");
            }
        }

        /// <summary>
        /// 开始游戏（通过SignalR调用）
        /// </summary>
        /// <param name="gameId">游戏ID</param>
        public async Task StartGame(string gameId)
        {
            try
            {
                if (!Guid.TryParse(gameId, out var parsedGameId))
                {
                    await Clients.Caller.SendAsync("Error", "无效的游戏ID");
                    return;
                }

                var userId = GetCurrentUserId();
                _logger.LogInformation("通过SignalR开始游戏: UserId={UserId}, GameId={GameId}", userId, gameId);

                var result = await _gameService.StartGameAsync(parsedGameId, userId);
                
                if (result.Success)
                {
                    // 广播游戏开始事件给整个游戏组
                    await Clients.Group($"Game_{gameId}").SendAsync("GameStarted", new
                    {
                        GameId = gameId,
                        StartTime = result.StartTime,
                        Duration = result.Duration,
                        Success = true,
                        Message = "游戏已开始"
                    });
                    
                    // 广播游戏状态更新
                    await Clients.Group($"Game_{gameId}").SendAsync("GameStateUpdate", result.GameState);
                    
                    _logger.LogInformation("游戏开始成功并已广播: GameId={GameId}", gameId);
                }
                else
                {
                    await Clients.Caller.SendAsync("GameStartRejected", new
                    {
                        Errors = result.Errors
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "通过SignalR开始游戏失败: GameId={GameId}", gameId);
                await Clients.Caller.SendAsync("Error", "开始游戏失败");
            }
        }

        /// <summary>
        /// 请求实时排名
        /// </summary>
        /// <param name="gameId">游戏ID</param>
        public async Task RequestRanking(string gameId)
        {
            try
            {
                _logger.LogInformation("🎯 客户端请求排行榜 - GameId: {GameId}, ConnectionId: {ConnectionId}", gameId, Context.ConnectionId);
                
                if (!Guid.TryParse(gameId, out var parsedGameId))
                {
                    _logger.LogWarning("🎯 无效的游戏ID - GameId: {GameId}", gameId);
                    await Clients.Caller.SendAsync("Error", "无效的游戏ID");
                    return;
                }

                var rankings = await _gameService.GetRealTimeRankingAsync(parsedGameId);
                
                _logger.LogInformation("🎯 获取到排行榜条目数: {Count}", rankings?.Count ?? 0);
                if (rankings?.Any() == true)
                {
                    foreach (var ranking in rankings)
                    {
                        _logger.LogInformation("🎯 排行榜条目单发前 - Rank: {Rank}, PlayerId: {PlayerId}, Username: {Username}, TerritoryArea: {TerritoryArea}",
                            ranking.Rank, ranking.PlayerId, ranking.Username, ranking.TerritoryArea);
                    }
                }
                
                await Clients.Caller.SendAsync("RankingUpdate", new
                {
                    rankings = rankings,
                    timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                });
                
                _logger.LogInformation("🎯 排行榜单发完成 - GameId: {GameId}, ConnectionId: {ConnectionId}", gameId, Context.ConnectionId);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "请求排名失败: GameId={GameId}", gameId);
                await Clients.Caller.SendAsync("Error", "获取排名失败");
            }
        }

        /// <summary>
        /// 玩家复活
        /// </summary>
        /// <param name="gameId">游戏ID</param>
        public async Task Respawn(string gameId)
        {
            try
            {
                if (!Guid.TryParse(gameId, out var parsedGameId))
                {
                    await Clients.Caller.SendAsync("Error", "无效的游戏ID");
                    return;
                }

                var userId = GetCurrentUserId();
                
                var result = await _gameService.RespawnPlayerAsync(parsedGameId, userId);
                
                if (result.Success)
                {
                    // 广播玩家复活事件
                    await Clients.Group($"Game_{gameId}").SendAsync("PlayerRespawned", new
                    {
                        PlayerId = userId.ToString(),
                        Position = result.SpawnPosition,
                        IsAlive = true,
                        Timestamp = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds()
                    });
                    
                    _logger.LogInformation("玩家复活成功: UserId={UserId}, GameId={GameId}", userId, gameId);
                }
                else
                {
                    await Clients.Caller.SendAsync("RespawnRejected", new
                    {
                        Errors = result.Errors
                    });
                    
                    _logger.LogWarning("玩家复活被拒绝: UserId={UserId}, GameId={GameId}, Errors={Errors}", 
                        userId, gameId, string.Join(", ", result.Errors));
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "玩家复活失败: GameId={GameId}", gameId);
                await Clients.Caller.SendAsync("Error", "复活失败");
            }
        }

        /// <summary>
        /// 连接建立时的处理
        /// </summary>
        public override async Task OnConnectedAsync()
        {
            var userId = GetCurrentUserId();
            _logger.LogInformation("玩家连接: UserId={UserId}, ConnectionId={ConnectionId}", userId, Context.ConnectionId);
            await base.OnConnectedAsync();
        }

        /// <summary>
        /// 连接断开时的处理
        /// </summary>
        /// <param name="exception">断开异常</param>
        public override async Task OnDisconnectedAsync(Exception? exception)
        {
            var userId = GetCurrentUserId();
            var userName = GetCurrentUserName();
            
            // 查找并移除所有相关游戏中的连接记录
            var disconnectedGames = new List<string>();
            foreach (var gameEntry in _gameConnections)
            {
                var gameId = gameEntry.Key;
                var gameConnections = gameEntry.Value;
                
                if (gameConnections.TryRemove(userId.ToString(), out _))
                {
                    disconnectedGames.Add(gameId);
                    
                    // 通知游戏内其他玩家有玩家断开连接
                    await Clients.Group($"Game_{gameId}").SendAsync("PlayerConnectionUpdate", new
                    {
                        PlayerId = userId.ToString(),
                        Username = userName,
                        IsConnected = false,
                        ConnectedCount = gameConnections.Count
                    });
                    
                    // 如果游戏没有玩家了，清理游戏连接记录
                    if (gameConnections.IsEmpty)
                    {
                        _gameConnections.TryRemove(gameId, out _);
                    }
                }
            }
            
            _logger.LogInformation("玩家断开连接: UserId={UserId}, ConnectionId={ConnectionId}, AffectedGames={Games}", 
                userId, Context.ConnectionId, string.Join(",", disconnectedGames));
                
            await base.OnDisconnectedAsync(exception);
        }

        /// <summary>
        /// 获取当前用户ID
        /// </summary>
        private Guid GetCurrentUserId()
        {
            var userIdClaim = Context.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value;
            if (Guid.TryParse(userIdClaim, out var userId))
            {
                return userId;
            }
            throw new UnauthorizedAccessException("无效的用户认证");
        }

        /// <summary>
        /// 获取当前用户名
        /// </summary>
        private string GetCurrentUserName()
        {
            return Context.User?.FindFirst(ClaimTypes.Name)?.Value ?? "Unknown";
        }
    }
}